import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:ball_lion/service/umeng_service.dart';
import 'package:ball_lion/entity/match/expert_views_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/utils/mode_config.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/items/expert_first_tag.dart';
import 'package:ball_lion/module/expert/items/expert_logo.dart';
import 'package:ball_lion/module/widget/history_label.dart';
import 'package:ball_lion/module/pick/items/expert_record_tag.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class ViewType {
  static const int scheduleView = 1;
  static const int startView = 2;
  static const int historyView = 3;
  static const int unknownView = 4;

  int typeCheck(int status) {
    switch (status) {
      case 1:
        return 1;
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
        return 2;
      case 7:
      case 8:
        return 3;
      default:
        return 4;
    }
  }

  static String playType(String type) {
    switch (type) {
      case "1001":
      case "1002":
        return "胜平负";
      case "1004":
        return "总进球";
      case "1005":
        return "半全场";
      case "1006":
        return "让球";
      case "1007":
        return "进球数";
      case "1008":
        return "胜平负";
      case "2001":
        return "胜负";
      case "2002":
        return "让分";
      case "2003":
        return "大小";
      default:
        return "未知";
    }
  }
}

class PlanItem extends StatelessWidget {
  const PlanItem(
      {super.key,
      required this.entity,
      this.isExpertDetailView = false,
      this.isMatchView = false,
      this.tabId,
      this.inList = false,
      this.liveJump = true,
      this.eventType,
      this.id,
      this.jumpParam});

  final bool isExpertDetailView;
  final bool isMatchView;
  final PlanEntity entity;
  final int? tabId;
  final bool inList;
  final bool liveJump;
  final String? eventType;
  final String? id;
  final Map<String, String>? jumpParam;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          try {
            if (eventType != null) {
              Utils.onEvent(eventType!,
                  params: {eventType!: entity.planId, "channel": id ?? ""});
            }
            Utils.onEvent('gdxq',
                params: {'gdxq': Get.currentRoute == Routes.viewpoint ? 5 : 0});
            if (Get.currentRoute == Routes.navigation) {
              // Get.find<UmengService>().payOriginRoute = 'tj_rmgd';
            }
            User.needLogin(() {
              Get.toNamed(Routes.viewpoint,
                  arguments: entity.planId,
                  parameters: jumpParam,
                  preventDuplicates: false);
            });
          } catch (e) {
            log(e.toString());
          }
        },
        child: entity.planStatus == null
            ? Container()
            : Stack(
                alignment: AlignmentDirectional.topEnd,
                clipBehavior: Clip.none,
                children: [
                  Container(
                    color: Colours.white,
                    child: Stack(children: [
                      Column(
                        children: [
                          isExpertDetailView
                              ? Container()
                              : Padding(
                                  padding: const EdgeInsets.only(top: 12),
                                  child: Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      GestureDetector(
                                          child: _planInfoWidget(),
                                          onTap: () async {
                                            if ((entity.liveInfo?.liveId
                                                        .hasValue ??
                                                    false) &&
                                                liveJump) {
                                              Get.toNamed(
                                                  entity.liveInfo
                                                              ?.liveSportsId ==
                                                          1
                                                      ? Routes.zqMatchDetail
                                                      : Routes.lqMatchDetail,
                                                  arguments:
                                                      entity.liveInfo?.matchId,
                                                  parameters: {
                                                    'roomId':
                                                        "${entity.liveInfo?.liveId}"
                                                  });
                                            } else {
                                              // Get.find<UmengService>()
                                              //     .payOriginRoute = 'zjzy';
                                              Get.toNamed(Routes.userPage,
                                                  arguments: entity.expertId,
                                                  parameters: {
                                                    'type': '2',
                                                    "index":
                                                        entity.sportsId == 1
                                                            ? 'zq'
                                                            : 'lq'
                                                  });
                                            }
                                          }),
                                      _returnRateWidget()
                                    ],
                                  ),
                                ),
                          Container(height: 6),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _contentWidget(),
                              isMatchView
                                  ? Container()
                                  : Padding(
                                      padding: const EdgeInsets.only(top: 10),
                                      child: _matchInfoWidget(),
                                    )
                            ],
                          ),
                          Container(height: 10),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              _timeAndViewsWidget(),
                              entity.planStatus == 0
                                  ? _moneyWidget()
                                  : const Row(
                                      children: [
                                        QsText("查看",
                                            fontSize: 12,
                                            color: Colours.grey66),
                                      ],
                                    )
                            ],
                          ),
                          if (entity.packInfo?.packageId != null)
                            GestureDetector(
                              behavior: HitTestBehavior.translucent,
                              onTap: () => Get.toNamed(Routes.planPackDetail,
                                  arguments: entity.packInfo?.packageId),
                              child: Container(
                                  margin:
                                      const EdgeInsets.only(top: 8, bottom: 6),
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 12, vertical: 5),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(13),
                                      border: Border.all(
                                          color: Colours.main, width: 0.5)),
                                  child: Row(children: [
                                    QsText(
                                      entity.packInfo?.content ?? "",
                                      fontSize: 12,
                                      color: Colours.main,
                                      needCenter: true,
                                    ),
                                    const Spacer(),
                                    Image.asset(
                                      Utils.getImgPath("arrow_right_36.png"),
                                      width: 12,
                                      height: 12,
                                      color: Colours.main,
                                    )
                                  ])),
                            ),
                          Container(height: inList ? 2 : 12)
                        ],
                      ),
                      if (entity.planStatus != 0)
                        Positioned(
                            right: 0,
                            bottom: isMatchView ? 35 : 50,
                            child: HistoryLabel.viewpoint(
                                width: 36, state: entity.planStatus ?? 0))
                    ]),
                  ),
                  // if (entity.activityId == 1 || entity.activityId == 2)
                  //   Positioned(
                  //     right: -12,
                  //     child: Image.asset(
                  //       Utils.getImgPath("buzhongtui.png"),
                  //       width: 36,
                  //       height: 36,
                  //     ),
                  //   )
                ],
              ));
  }

  Widget _planInfoWidget() {
    return Row(
      children: [
        ExpertLogo(
            logo: entity.expertLogo,
            inLive: entity.liveInfo?.liveId.hasValue,
            hasAuth: entity.isInvite == 1),
        Container(width: 7),
        Column(
          mainAxisAlignment: ModeConfig.expertRecord
              ? MainAxisAlignment.center
              : MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                QsText(entity.expertName ?? '',
                    needCenter: true, fontWeight: FontWeight.w500),
                if (ModeConfig.expertRecord && entity.firstTag.hasValue) ...[
                  Container(width: 4),
                  ExpertFirstTag(tag: entity.firstTag!)
                ]
              ],
            ),
            if (ModeConfig.expertRecord && entity.secondTag.hasValue) ...[
              Container(height: 2),
              ExpertRecordTag(type: 5, text: entity.secondTag)
            ]
          ],
        )
      ],
    );
  }

  Widget _returnRateWidget() {
    if (!ModeConfig.expertRecord) {
      return Container(height: 50);
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        QsText((entity.value ?? ""),
            fontSize: 24,
            fontFamily: "Din",
            fontWeight: FontWeight.w700,
            color: Colours.main,
            letterSpacing: -2,
            height: 1),
        QsText(
          (entity.description ?? ''),
          color: Colours.main,
          fontSize: 9,
          height: 1,
        )
      ],
    );
  }

  Widget _contentWidget() {
    return RichText(
        maxLines: 2,
        softWrap: true,
        overflow: TextOverflow.ellipsis,
        text: TextSpan(
            // style: const TextStyle(fontSize: 1.2),
            children: [
              if (entity.playTypeName != null)
                TextSpan(
                    text: "[${entity.playTypeName ?? ""}]",
                    style: const TextStyle(
                        fontSize: 17, color: Color(0xFF39407E))),
              if (entity.isVideo == 1)
                WidgetSpan(
                    baseline: TextBaseline.ideographic,
                    alignment: PlaceholderAlignment.baseline,
                    child: Image.asset(Utils.getImgPath("inner_video.png"),
                            width: 16, height: 16)
                        .paddingSymmetric(horizontal: 4))
              else
                const TextSpan(text: "\u2000"),
              TextSpan(
                text: entity.planTitle == '' || entity.planTitle == null
                    ? "暂无内容"
                    : entity.planTitle!,
                style: const TextStyle(fontSize: 17, color: Colours.text),
              ).formHighLight()
            ]));
  }

  Widget _matchInfoWidget() {
    return Column(
        children: List.generate(
      entity.matchBries?.length ?? 0,
      (index) => Container(
          width: Get.width,
          padding: const EdgeInsets.symmetric(vertical: 4.5, horizontal: 10),
          decoration: BoxDecoration(
              color: Colours.greyF7FAFF,
              borderRadius: BorderRadius.circular(5)),
          child:
              _matchInfoItem(entity.matchBries?[index], entity.sportsId ?? 1)),
    ).insertEvery(Container(height: 2)));
  }

  Widget _matchInfoItem(MatchBries? match, int sportsId) {
    return DefaultTextStyle(
      style: const TextStyle(fontSize: 12, color: Colours.grey99),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          QsText("[${sportsId == 1 ? "足" : "篮"}]\u2000",
              color: Colours.blue2766D6),
          QsText(
            "${DateTime.parse(match?.matchTime ?? '').formatedString("MM/dd HH:mm") ?? "时间暂无"}\u2000",
            height: 1.5,
          ),
          Container(
              width: 0.5,
              height: 10,
              alignment: Alignment.center,
              color: Colours.greyE0E1E5),
          QsText("\u2000${match?.leagueName ?? "未知联赛"}\u2000"),
          Flexible(
            child: QsText(
              sportsId == 1
                  ? match?.homeName ?? "主队未知"
                  : match?.guestName ?? "客队未知",
              maxLines: 1,
              fontSize: 12,
              color: Colours.grey99,
            ).formHighLight(),
          ),
          const QsText("\u2000"),
          match?.status == 1 || entity.planStatus == 3
              ? const QsText("vs")
              : sportsId == 1
                  ? QsText(
                      "${match?.homeScore90}:${match?.guestScore90}",
                    )
                  : QsText(
                      "${match?.guestScore}:${match?.homeScore}",
                    ),
          const QsText("\u2000"),
          Flexible(
            child: QsText(
              sportsId == 1
                  ? match?.guestName ?? "客队未知"
                  : match?.homeName ?? "主队未知",
              maxLines: 1,
              fontSize: 12,
              color: Colours.grey99,
            ).formHighLight(),
          ),
        ],
      ),
    );
  }

  Widget _timeAndViewsWidget() {
    return Row(
      children: [
        if (entity.planPublicTime != null)
          QsText(
                  Utils.formatTime(DateTime.parse(entity.planPublicTime ?? "")
                      .millisecondsSinceEpoch),
                  fontSize: 12,
                  color: Colours.grey99)
              .paddingOnly(right: 8),
        QsText("${entity.pv}人感兴趣", fontSize: 12, color: Colours.grey99)
      ],
    );
  }

  Widget _moneyWidget() {
    return Row(
      children: [
        if (entity.priceReal != entity.price && entity.price.hasValue)
          QsText(
            "${checkMoney(entity.price!)}球币".changeUnit,
            fontSize: 12,
            color: Colours.grey66,
            decoration: TextDecoration.lineThrough,
            decorationStyle: TextDecorationStyle.solid,
          ),
        Container(width: 10),
        // if(!(entity.priceReal == "0.00"))
        // Image.asset(Utils.getImgPath("gold_icon.png"),width: 16),
        // Container(width: 3),
        QsText(
          entity.priceCoupon.hasValue
              ? "券后${checkMoney(entity.priceCoupon!)}球币".changeUnit
              : entity.priceReal.noValue
                  ? ''
                  : entity.priceReal == "0.00"
                      ? "免费查看"
                      : "${checkMoney(entity.priceReal!)}球币".changeUnit,
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color: entity.priceReal == "0.00" ? Colours.yellow : Colours.main,
        ),
        if (entity.activityId == 1 ||
            entity.activityId == 2 ||
            entity.activityId == 3)
          Padding(
            padding: const EdgeInsets.only(left: 8),
            child: Image.asset(
              entity.activityId == 3
                  ? Utils.getImgPath("vip_free_tag.png")
                  : Utils.getImgPath("buzhongtui.png"),
              width: entity.activityId == 3 ? 58 : 34,
              height: entity.activityId == 3 ? 15 : 14,
            ),
          )
      ],
    );
  }

  checkMoney(String price) {
    var check = price.split('.');
    if (check[1] == '00') {
      return check[0];
    } else if (check[1].split('')[0] != '0' && check[1].split('')[1] == '0') {
      return "${check[0]}.${check[1].split('')[0]}";
    } else {
      return price;
    }
  }
}
